package com.toocms.jinjuhang.ui.mine.apply_cooperation

import android.app.Application
import android.text.TextUtils
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Region
import com.toocms.jinjuhang.config.UploadType
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.ApplyPageData
import com.toocms.jinjuhang.data.center.ApplyPageTypeData
import com.toocms.jinjuhang.data.system.RegionItemData
import com.toocms.jinjuhang.data.system.UploadData
import com.toocms.jinjuhang.dialog.options.OptionsDialog
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseActivity
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.widget.picker.OptionsPickerView
import com.toocms.tab.widget.picker.builder.OptionsPickerBuilder

class ApplyCooperationModel(application: Application) : BaseViewModel<BaseModel>(application) {
    val TYPE_ORGANIZATION = "1" //机构
    val TYPE_AMBASSADOR = "2" //大使
    val TYPE_ATTACHE = "3" //专员

    var optionsPickerView: (OptionsPickerView<RegionItemData>)? = null

    val pageDataObservableField = ObservableField<ApplyPageData>()
    var type: String? = null
    var organizationId: String? = null
    var latitude: String? = null
    var longitude: String? = null
    val typeNameObservableField = ObservableField<String>()
    val realNameObservableField = ObservableField<String>()
    val cardNoObservableField = ObservableField<String>()
    val mobileObservableField = ObservableField<String>()
    val adcodeObservableField = ObservableField<String>()
    val cardFIdObservableField = ObservableField<String>()
    val cardFUrlObservableField = ObservableField<String>()
    val cardBIdObservableField = ObservableField<String>()
    val cardBUrlObservableField = ObservableField<String>()
    val licenseIdObservableField = ObservableField<String>()
    val licenseUrlObservableField = ObservableField<String>()
    val permitIdObservableField = ObservableField<String>()
    val permitUrlObservableField = ObservableField<String>()
    val agreementIdObservableField = ObservableField<String>()
    val agreementUrlObservableField = ObservableField<String>()
    val formattedAddressObservableField = ObservableField<String>()

    val supplementaryMaterialsImageItems =
        ObservableArrayList<ApplyCooperationSupplementaryMaterialsImageItemModel>()
    val supplementaryMaterialsImageItemBinding =
        ItemBinding.of<ApplyCooperationSupplementaryMaterialsImageItemModel>(
            BR.applyCooperationSupplementaryMaterialsImageItemModel,
            R.layout.item_supplementary_materials_image
        )

    val applyOrganisationClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        var types = pageDataObservableField.get()?.type ?: return@BindingAction
        OptionsDialog().apply {
            title = StringUtils.getString(R.string.str_applicant_organisation_hint)
            optionsItems = types
            onOptionClickListener = { options, _ ->
                if (options is ApplyPageTypeData) {
                    type = options.value
                    typeNameObservableField.set(options.name)
                }
            }
        }.show((ActivityUtils.getTopActivity() as BaseActivity).supportFragmentManager, null)
    })

    val promotionAreaClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
//        TabMapApi.getChoosingApi().startNearPoiPageForResult(this) { poiItem ->
//            adcodeObservableField.set(poiItem.adCode)
//            formattedAddressObservableField.set("${poiItem.provinceName} ${poiItem.cityName} ${poiItem.adName}")
//        }
        val localRegion = Region.localRegion
        if (null == localRegion) {
            showToast("正在获取地址列表,请稍后再试")
            return@BindingAction
        }
        val province = localRegion?.province ?: ArrayList()
        val city = localRegion?.city ?: ArrayList()
        val district = localRegion?.district ?: ArrayList()
        optionsPickerView = OptionsPickerBuilder(
            ActivityUtils.getTopActivity()
        ) { view, options1, options2, options3 ->
            adcodeObservableField.set(district[options1][options2][options3].id)
            formattedAddressObservableField.set("${province[options1].region_name} ${city[options1][options2].region_name} ${district[options1][options2][options3].region_name}")
            optionsPickerView?.dismiss()
            return@OptionsPickerBuilder true
        }.run {
            setTitleText("推广区域")
            setDividerColor(0x00000000)
            setLabels("", "", "")
            build<RegionItemData>()
        }.apply {
            setPicker(
                province,
                city,
                district
            )
            show()
        }
    })

    val cardFClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectImage(UploadType.ID_CARD_FRONTAL)
    })

    val cardFDeleteClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        cardFIdObservableField.set("")
        cardFUrlObservableField.set("")
    })

    val cardBClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectImage(UploadType.ID_CARD_BACK)
    })

    val cardBDeleteClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        cardBIdObservableField.set("")
        cardBUrlObservableField.set("")
    })

    val businessLicenseClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectImage(UploadType.BUSINESS_LICENSE)
    })

    val businessLicenseDeleteClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        licenseIdObservableField.set("")
        licenseUrlObservableField.set("")
    })

    val permitClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectImage(UploadType.OPENING_BANK_PERMIT)
    })

    val permitDeleteClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        permitIdObservableField.set("")
        permitUrlObservableField.set("")
    })

    val agreementClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectImage(UploadType.COOPERATION_AGREEMENT)
    })

    val agreementDeleteClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        agreementIdObservableField.set("")
        agreementUrlObservableField.set("")
    })

    val commitApplyClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["type"] = type
        params["real_name"] = realNameObservableField.get()
        params["card_no"] = cardNoObservableField.get()
        params["mobile"] = mobileObservableField.get()
        params["adcode"] = adcodeObservableField.get()
        params["card_f"] = cardFIdObservableField.get()
        params["card_b"] = cardBIdObservableField.get()
        params["license"] = licenseIdObservableField.get()
        params["permit"] = permitIdObservableField.get()
        params["agreement"] = agreementIdObservableField.get()
        params["others"] = supplementaryMaterialsImageIds()
        params["formatted_address"] = formattedAddressObservableField.get()
        params["organization_id"] = organizationId
        params["longitude"] = longitude
        params["latitude"] = latitude
        requestData(
            Urls.Center.ORGANIZATION_APPLY,
            params,
            resultClass = String::class.java,
            isShowLoading = true,
            result = {
                showToast(it)
                finishFragment()
            })
    })

    init {
        applypage()
        supplementaryMaterialsImageItems += ApplyCooperationSupplementaryMaterialsImageItemModel(
            this
        )
    }

    private fun applypage() {
        requestData(Urls.Center.APPLY_PAGE,
            mapOf(Pair("member_id", UserRepository.user.member_id)),
            resultClass = ApplyPageData::class.java,
            result = {
                organizationId = it.organization_id
                if (organizationId.isNullOrEmpty() || "0" == organizationId) {
                    type = TYPE_ORGANIZATION
                    typeNameObservableField.set(StringUtils.getString(R.string.str_organization))
                    it.type = null
                }
                pageDataObservableField.set(it)
            })
    }


    private fun supplementaryMaterialsImageIds(): String {
        val result = StringBuilder()
        supplementaryMaterialsImageItems.forEach {
            val imageId = it.item.get()?.id ?: return@forEach
            if (result.isNotEmpty()) result.append(Constants.Extra.DECOLLATOR_DEFAULT)
            result.append(imageId)
        }
        return result.toString()
    }

    fun selectImage(type: UploadType) {
        when (type) {
            UploadType.ID_CARD_FRONTAL, UploadType.ID_CARD_BACK -> {
                startSelectSignImageAty(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                        val paths = ArrayList<String>()
                        result?.forEach {
                            paths += it.realPath
                        }
                        imageUpload(paths, type)
                    }

                    override fun onCancel() {
                    }

                }, 27, 19)

            }

            UploadType.BUSINESS_LICENSE, UploadType.OPENING_BANK_PERMIT, UploadType.COOPERATION_AGREEMENT, UploadType.SUPPLEMENTARY_MATERIALS -> {
                val selectedMaxImageNumber = if (UploadType.SUPPLEMENTARY_MATERIALS != type) {
                    1
                } else {
                    if (!supplementaryMaterialsImageItems.isNullOrEmpty() && TextUtils.isEmpty(
                            supplementaryMaterialsImageItems[0].item.get()?.id ?: ""
                        )
                    ) {
                        Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER - supplementaryMaterialsImageItems.size + 1
                    } else {
                        Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER - supplementaryMaterialsImageItems.size
                    }
                }
                startSelectMultipleImageAty(
                    null,
                    selectedMaxImageNumber,
                    object : OnResultCallbackListener<LocalMedia> {
                        override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                            val paths = ArrayList<String>()
                            result?.forEach {
                                paths += it.realPath
                            }
                            imageUpload(paths, type)
                        }

                        override fun onCancel() {
                        }

                    })
            }
        }
    }

    private fun imageUpload(imagePaths: List<String>, type: UploadType) {
        if (imagePaths.isNullOrEmpty()) return
        val pathsParams = mutableMapOf<String, String?>()
        imagePaths.forEachIndexed { index, path ->
            pathsParams["iamge$index"] = path
        }
        requestData(Urls.System.UPLOAD,
            filePaths = pathsParams,
            resultClass = UploadData::class.java,
            isShowLoading = true,
            result = {
                it.list?.apply {
                    if (isNullOrEmpty()) return@apply
                    when (type) {
                        UploadType.ID_CARD_FRONTAL -> {
                            cardFIdObservableField.set(this[0].id)
                            cardFUrlObservableField.set(this[0].abs_url)
                        }

                        UploadType.ID_CARD_BACK -> {
                            cardBIdObservableField.set(this[0].id)
                            cardBUrlObservableField.set(this[0].abs_url)
                        }

                        UploadType.BUSINESS_LICENSE -> {
                            licenseIdObservableField.set(this[0].id)
                            licenseUrlObservableField.set(this[0].abs_url)
                        }

                        UploadType.OPENING_BANK_PERMIT -> {
                            permitIdObservableField.set(this[0].id)
                            permitUrlObservableField.set(this[0].abs_url)
                        }

                        UploadType.COOPERATION_AGREEMENT -> {
                            agreementIdObservableField.set(this[0].id)
                            agreementUrlObservableField.set(this[0].abs_url)
                        }

                        UploadType.SUPPLEMENTARY_MATERIALS -> {
                            forEach {
                                supplementaryMaterialsImageItems += ApplyCooperationSupplementaryMaterialsImageItemModel(
                                    this@ApplyCooperationModel, ObservableField(it)
                                )
                            }
                            if (Constants.Extra.EVALUATE_UPLOAD_IMAGE_MAX_NUMBER < supplementaryMaterialsImageItems.size && TextUtils.isEmpty(
                                    supplementaryMaterialsImageItems[0].item.get()?.id
                                )
                            ) {
                                supplementaryMaterialsImageItems.remove(
                                    supplementaryMaterialsImageItems[0]
                                )
                            }
                        }
                    }
                }
            })
    }


}